<!DOCTYPE html>

<html lang="en">
  <head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>多语言支持（Multi-lingual Support） &mdash; Phalcon 3.0.1 文档</title>
    <meta name="keywords" content="php, phalcon, phalcon php, php framework, faster php framework">
    <link rel="stylesheet" type="text/css" href="http://cdn.staticfile.org/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="/www/css/phalcon.min.css" />
    <link href='//fonts.googleapis.com/css?family=Open+Sans:700,400' rel='stylesheet' type='text/css'>
    <link href="//fonts.googleapis.com/css?family=Merriweather:400,700" rel="stylesheet" type="text/css" />
    <!--
    EUROPE <link href='//fonts.googleapis.com/css?family=Open+Sans:700,400&subset=latin-ext' rel='stylesheet' type='text/css'>
    GREEK <link href='//fonts.googleapis.com/css?family=Open+Sans:700,400&subset=greek-ext' rel='stylesheet' type='text/css'>
    RUSSIA <link href='//fonts.googleapis.com/css?family=Open+Sans:700,400&subset=cyrillic-ext,latin' rel='stylesheet' type='text/css'>
    -->

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <link rel="stylesheet" href="../static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../static/docs.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.0.1',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>

    <script src="http://cdn.staticfile.org/jquery/1.8.1/jquery.min.js"></script>
    <script type="text/javascript" src="../static/docs.js"></script>
    <link rel="shortcut icon" href="../static/favicon.ico"/>
    <link rel="top" title="Phalcon 3.0.1 文档" href="../index.html" />
    <link rel="next" title="Class Autoloader" href="loader.html" />
    <link rel="prev" title="访问控制列表 ACL（Access Control Lists ACL）" href="acl.html" /> 
  </head>
  <body>

<header class="page-header">
    <nav class="navbar" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-menu-container">
                    <span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
                </button>
                <a class="navbar-brand phalcon-logo" href="/"><span itemprop="name" class="sr-only">Phalcon PHP</span></a>
            </div>

            <div class="collapse navbar-collapse navbar-right" id="main-menu-container">
                <ul class="nav navbar-nav main-menu">
                  <li class="first"><a href="//phalconphp.com/en/download" class="header-nav-link">Download</a></li>
                  <li><a href="//docs.phalconphp.com/en/latest/index.html" class="header-nav-link" target="_blank">Documentation</a></li>
                  <li><a href="//forum.phalconphp.com/" class="header-nav-link" target="_blank">Forum</a></li>
                  <li><a href="//blog.phalconphp.com/" class="header-nav-link" target="_blank">Blog</a></li>
                  <li><a href="//phalconist.com/" class="header-nav-link" target="_blank">Resources</a></li>
                  <li><a href="//phalconphp.com/en/about">About</a></li>
                  <li><div align="right">
                      <iframe src="https://ghbtns.com/github-btn.html?user=phalcon&amp;repo=cphalcon&amp;type=watch&amp;count=true&amp;size=large"
      allowtransparency="true" frameborder="0" scrolling="0" width="152px" height="30px"></iframe>
                    </div></li>
                </ul>
            </div>
        </div>
    </nav>
  </header>

<div class="heading">
    <div class="container">
        <div class="row">
            <h2>Documentation</h2>
        </div>
    </div>
</div>
    <div class="related">
      <ul>
        <li class="right" >
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="loader.html" title="Class Autoloader"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="acl.html" title="访问控制列表 ACL（Access Control Lists ACL）"
             accesskey="P">上一页</a> |</li>
        <li><a href="//phalconphp.com">Home</a> &raquo;</li>
        <li><a href="../index.html">Phalcon 3.0.1 文档</a> &raquo;</li> 
      </ul>
    </div>  

      <table width="100%" align="center" cellpadding="0" cellspacing="0">
        <tr>
      <td class="primary-box" width="25%" valign="top">
            <div>
            <div id="searchbox" style="">
                <!--<form class="search" action="http://readthedocs.org/search/project/" method="get">
                  <input type="search" name="q" size="25" placeholder="Search">
                  <input type="submit" value="Go">
                  <input type="hidden" name="selected_facets" value="project:">
                </form>-->
                <div style="width:200px;padding:10px">
                  <gcse:searchbox-only></gcse:searchbox-only>
                </div>
            </div>
            </div>
            <div style="padding:5px;padding-left:10px">
              <div id="carbonads-container">
                <div class="carbonad"><div id="azcarbon"></div>
                <script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=phalconphpcom" id="_carbonads_js"></script>
                </div></div>
            </div>
            <h3><a href="../index.html">內容目录</a></h3>
            <ul>
<li><a class="reference internal" href="#">多语言支持（Multi-lingual Support）</a><ul>
<li><a class="reference internal" href="#adapters">适配器（Adapters）</a></li>
<li><a class="reference internal" href="#component-usage">组件的使用（Component Usage）</a></li>
<li><a class="reference internal" href="#implementing-your-own-adapters">自定义适配器（Implementing your own adapters）</a></li>
</ul>
</li>
</ul>

            <h4>上一个主题</h4>
            <p class="topless"><a href="acl.html" title="上一章">&lt; 访问控制列表 ACL（Access Control Lists ACL）</a></p>
            <h4>下一个主题</h4>
            <p class="topless"><a href="loader.html" title="下一章">Class Autoloader &gt;</a></p>
            <h3>本页</h3>
            <ul class="this-page-menu">
              <li><a href="../sources/reference/translate.md" rel="nofollow">显示源代码</a></li>
            </ul>
        </td>
          <td class="second-box" valign="top">
            <div class="document">
                <div class="documentwrapper">
                  <div class="bodywrapper">
                    <div class="body" >
                      
  <div class="section" id="multi-lingual-support">
<h1>多语言支持（Multi-lingual Support）<a class="headerlink" href="#multi-lingual-support" title="永久链接至标题">¶</a></h1>
<p>The component <a class="reference internal" href="../api/Phalcon_Translate.html"><em>Phalcon\Translate</em></a> aids in creating multilingual applications.
Applications using this component, display content in different languages, based on the user&#8217;s chosen language supported by the application.</p>
<div class="section" id="adapters">
<h2>适配器（Adapters）<a class="headerlink" href="#adapters" title="永久链接至标题">¶</a></h2>
<p>This component makes use of adapters to read translation messages from different sources in a unified way.</p>
<table border="1" class="docutils">
<colgroup>
<col width="52%" />
<col width="48%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Adapter</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="../api/Phalcon_Translate_Adapter_NativeArray.html"><em>Phalcon\Translate\Adapter\NativeArray</em></a></td>
<td>Uses PHP arrays to store the messages. This is the best option in terms of performance.</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="component-usage">
<h2>组件的使用（Component Usage）<a class="headerlink" href="#component-usage" title="永久链接至标题">¶</a></h2>
<p>Translation strings are stored in files. The structure of these files could vary depending of the adapter used. Phalcon gives you the freedom
to organize your translation strings. A simple structure could be:</p>
<div class="highlight-bash"><div class="highlight"><pre>app/messages/en.php
app/messages/es.php
app/messages/fr.php
app/messages/zh.php
</pre></div>
</div>
<p>Each file contains an array of the translations in a key/value manner. For each translation file, keys are unique. The same array is used in
different files, where keys remain the same and values contain the translated strings depending on each language.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="c1">// app/messages/en.php</span>
<span class="nv">$messages</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s2">&quot;hi&quot;</span>      <span class="o">=&gt;</span> <span class="s2">&quot;Hello&quot;</span><span class="p">,</span>
    <span class="s2">&quot;bye&quot;</span>     <span class="o">=&gt;</span> <span class="s2">&quot;Good Bye&quot;</span><span class="p">,</span>
    <span class="s2">&quot;hi-name&quot;</span> <span class="o">=&gt;</span> <span class="s2">&quot;Hello %name%&quot;</span><span class="p">,</span>
    <span class="s2">&quot;song&quot;</span>    <span class="o">=&gt;</span> <span class="s2">&quot;This song is %song%&quot;</span><span class="p">,</span>
<span class="p">];</span>
</pre></div>
</div>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="c1">// app/messages/fr.php</span>
<span class="nv">$messages</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s2">&quot;hi&quot;</span>      <span class="o">=&gt;</span> <span class="s2">&quot;Bonjour&quot;</span><span class="p">,</span>
    <span class="s2">&quot;bye&quot;</span>     <span class="o">=&gt;</span> <span class="s2">&quot;Au revoir&quot;</span><span class="p">,</span>
    <span class="s2">&quot;hi-name&quot;</span> <span class="o">=&gt;</span> <span class="s2">&quot;Bonjour %name%&quot;</span><span class="p">,</span>
    <span class="s2">&quot;song&quot;</span>    <span class="o">=&gt;</span> <span class="s2">&quot;La chanson est %song%&quot;</span><span class="p">,</span>
<span class="p">];</span>
</pre></div>
</div>
<p>Implementing the translation mechanism in your application is trivial but depends on how you wish to implement it. You can use an
automatic detection of the language from the user&#8217;s browser or you can provide a settings page where the user can select their language.</p>
<p>A simple way of detecting the user&#8217;s language is to parse the <code class="code docutils literal"><span class="pre">$_SERVER['HTTP_ACCEPT_LANGUAGE']</span></code> contents, or if you wish, access it
directly by calling <code class="code docutils literal"><span class="pre">$this-&gt;request-&gt;getBestLanguage()</span></code> from an action/controller:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>
<span class="k">use</span> <span class="nx">Phalcon\Translate\Adapter\NativeArray</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">UserController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="k">function</span> <span class="nf">getTranslation</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="c1">// Ask browser what is the best language</span>
        <span class="nv">$language</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">request</span><span class="o">-&gt;</span><span class="na">getBestLanguage</span><span class="p">();</span>

        <span class="nv">$translationFile</span> <span class="o">=</span> <span class="s2">&quot;app/messages/&quot;</span> <span class="o">.</span> <span class="nv">$language</span> <span class="o">.</span> <span class="s2">&quot;.php&quot;</span><span class="p">;</span>

        <span class="c1">// Check if we have a translation file for that lang</span>
        <span class="k">if</span> <span class="p">(</span><span class="nb">file_exists</span><span class="p">(</span><span class="nv">$translationFile</span><span class="p">))</span> <span class="p">{</span>
            <span class="k">require</span> <span class="nv">$translationFile</span><span class="p">;</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="c1">// Fallback to some default</span>
            <span class="k">require</span> <span class="s2">&quot;app/messages/en.php&quot;</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="c1">// Return a translation object</span>
        <span class="k">return</span> <span class="k">new</span> <span class="nx">NativeArray</span><span class="p">(</span>
            <span class="p">[</span>
                <span class="s2">&quot;content&quot;</span> <span class="o">=&gt;</span> <span class="nv">$messages</span><span class="p">,</span>
            <span class="p">]</span>
        <span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">indexAction</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">view</span><span class="o">-&gt;</span><span class="na">name</span> <span class="o">=</span> <span class="s2">&quot;Mike&quot;</span><span class="p">;</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">view</span><span class="o">-&gt;</span><span class="na">t</span>    <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getTranslation</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The <code class="code docutils literal"><span class="pre">_getTranslation()</span></code> method is available for all actions that require translations. The <code class="code docutils literal"><span class="pre">$t</span></code> variable is passed to the views, and with it,
we can translate strings in that layer:</p>
<div class="highlight-html+php"><div class="highlight"><pre><span class="c">&lt;!-- welcome --&gt;</span>
<span class="c">&lt;!-- String: hi =&gt; &#39;Hello&#39; --&gt;</span>
<span class="nt">&lt;p&gt;</span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$t</span><span class="o">-&gt;</span><span class="na">_</span><span class="p">(</span><span class="s2">&quot;hi&quot;</span><span class="p">),</span> <span class="s2">&quot; &quot;</span><span class="p">,</span> <span class="nv">$name</span><span class="p">;</span> <span class="cp">?&gt;</span><span class="nt">&lt;/p&gt;</span>
</pre></div>
</div>
<p>The <code class="code docutils literal"><span class="pre">_()</span></code> method is returning the translated string based on the index passed. Some strings need to incorporate placeholders for
calculated data i.e. Hello %name%. These placeholders can be replaced with passed parameters in the <code class="code docutils literal"><span class="pre">_()</span></code> method. The passed parameters
are in the form of a key/value array, where the key matches the placeholder name and the value is the actual data to be replaced:</p>
<div class="highlight-html+php"><div class="highlight"><pre><span class="c">&lt;!-- welcome --&gt;</span>
<span class="c">&lt;!-- String: hi-name =&gt; &#39;Hello %name%&#39; --&gt;</span>
<span class="nt">&lt;p&gt;</span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$t</span><span class="o">-&gt;</span><span class="na">_</span><span class="p">(</span><span class="s2">&quot;hi-name&quot;</span><span class="p">,</span> <span class="p">[</span><span class="s2">&quot;name&quot;</span> <span class="o">=&gt;</span> <span class="nv">$name</span><span class="p">]);</span> <span class="cp">?&gt;</span><span class="nt">&lt;/p&gt;</span>
</pre></div>
</div>
<p>Some applications implement multilingual on the URL such as <a class="reference external" href="http://www.mozilla.org/">http://www.mozilla.org/</a><strong>es-ES</strong>/firefox/. Phalcon can implement
this by using a <a class="reference internal" href="routing.html"><em>Router</em></a>.</p>
</div>
<div class="section" id="implementing-your-own-adapters">
<h2>自定义适配器（Implementing your own adapters）<a class="headerlink" href="#implementing-your-own-adapters" title="永久链接至标题">¶</a></h2>
<p>The <a class="reference internal" href="../api/Phalcon_Translate_AdapterInterface.html"><em>Phalcon\Translate\AdapterInterface</em></a> interface must be implemented
in order to create your own translate adapters or extend the existing ones:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Translate\AdapterInterface</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">MyTranslateAdapter</span> <span class="k">implements</span> <span class="nx">AdapterInterface</span>
<span class="p">{</span>
    <span class="sd">/**</span>
<span class="sd">     * Adapter constructor</span>
<span class="sd">     *</span>
<span class="sd">     * @param array $data</span>
<span class="sd">     */</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nv">$options</span><span class="p">);</span>

    <span class="sd">/**</span>
<span class="sd">     * Returns the translation string of the given key</span>
<span class="sd">     *</span>
<span class="sd">     * @param   string $translateKey</span>
<span class="sd">     * @param   array $placeholders</span>
<span class="sd">     * @return  string</span>
<span class="sd">     */</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">_</span><span class="p">(</span><span class="nv">$translateKey</span><span class="p">,</span> <span class="nv">$placeholders</span> <span class="o">=</span> <span class="k">null</span><span class="p">);</span>

    <span class="sd">/**</span>
<span class="sd">     * Returns the translation related to the given key</span>
<span class="sd">     *</span>
<span class="sd">     * @param   string $index</span>
<span class="sd">     * @param   array $placeholders</span>
<span class="sd">     * @return  string</span>
<span class="sd">     */</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">query</span><span class="p">(</span><span class="nv">$index</span><span class="p">,</span> <span class="nv">$placeholders</span> <span class="o">=</span> <span class="k">null</span><span class="p">);</span>

    <span class="sd">/**</span>
<span class="sd">     * Check whether is defined a translation key in the internal array</span>
<span class="sd">     *</span>
<span class="sd">     * @param   string $index</span>
<span class="sd">     * @return  bool</span>
<span class="sd">     */</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">exists</span><span class="p">(</span><span class="nv">$index</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>There are more adapters available for this components in the <a class="reference external" href="https://github.com/phalcon/incubator/tree/master/Library/Phalcon/Translate/Adapter">Phalcon Incubator</a></p>
</div>
</div>


                    </div>
                  </div>
                </div>
            </div>
          </td>
        </tr>
      </table>
    <div class="related">
      <ul>
        <li class="right" >
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="loader.html" title="Class Autoloader"
             >下一页</a> |</li>
        <li class="right" >
          <a href="acl.html" title="访问控制列表 ACL（Access Control Lists ACL）"
             >上一页</a> |</li> 
      </ul>
    </div>

      <div class="prefooter">
  <div class="container">
      <div class="row">
          <div class="col-sm-3 text-right">
              <span>Follow along:</span>
          </div>
          <div class="col-sm-6 text-center">
              <a href="https://twitter.com/phalconphp" alt="Twitter" class="btn-social btn-social-twitter"><i class="icon-twitter"></i></a>
              <a href="https://www.facebook.com/pages/Phalcon-Framework/134230726685897" alt="Facebook" class="btn-social btn-social-facebook"><i class="icon-facebook"></i></a>
              <a href="https://plus.google.com/102376109340560896457" alt="Google+" class="btn-social btn-social-googleplus"><i class="icon-googleplus"></i></a>
              <a href="https://github.com/phalcon/cphalcon" alt="Github" class="btn-social btn-social-github"><i class="icon-github"></i></a>
          </div>
          <div class="col-sm-3">
          </div>
      </div>
  </div>

</div>
<footer class="footer">
    <div class="container">
        <div class="row">
            <div class="col-xs-4 col-sm-3">
                <h4>Download</h4>
                <ul>
                    <li><a href="/download">Installing Phalcon PHP</a></li>
                    <li><a href="http://docs.phalconphp.com/en/latest/index.html" class="header-nav-link" target="_blank">Documentation</a></li>
                    <li><a href="http://api.phalconphp.com">API</a></li>
                    <li><a href="http://docs.phalconphp.com/en/latest/reference/tutorial.html">Tutorial</a></li>
                    <li><a href="http://docs.phalconphp.com/en/latest/reference/tutorial.html#sample-applications">Sample Applications</a></li>
                </ul>
            </div>
            <div class="col-xs-4 col-sm-3">
                <h4>Community</h4>
                <ul>
                    <li><a href="http://forum.phalconphp.com/" class="header-nav-link" target="_blank">Forum</a></li>
                    <li><a href="https://github.com/phalcon/cphalcon">GitHub</a></li>
                    <li><a href="https://github.com/phalcon/cphalcon/issues">Issue Tracker</a></li>
                    <li><a href="http://stackoverflow.com/questions/tagged/phalcon">Stack Overflow</a></li>
                    <li><a href="/en/testimonials">Testimonials</a></li>
                    <li><a href="http://builtwith.phalconphp.com/">Built with Phalcon</a></li>
                    <li><a href="http://store.phalconphp.com/">Store</a></li>
                </ul>
            </div>
            <div class="col-xs-4 col-sm-2">
                <h4>About</h4>
                <ul>
                    <li><a class="link-black" href="http://blog.phalconphp.com/">Blog</a></li>
                    <li><a href="/en/about">About</a></li>
                    <li><a href="/en/team">Team</a></li>
                    <li><a href="/en/roadmap">Roadmap</a></li>
                    <li><a href="/en/donate">Donate</a></li>
                    <li><a href="/en/consulting">Consulting</a></li>
                    <li><a href="/en/hosting">Hosting</a></li>
                </ul>
            </div>
            <div id="license-spaccer" class="visible-xs"></div>
            <div id="license-wrapper" class="col-xs-12 col-sm-4">
                <p class="license">
                    Phalcon is an open-source PHP framework <br>built as a C-extension. It is available under the <br>
                    <a href="http://opensource.org/licenses/BSD-3-Clause" target="_blank">new BSD License</a>.
                    <br>
                    <br>
                    Except where otherwise noted, content on this site is licensed under the
                    <a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 License.</a>
                </p>
            </div>
        </div>
    </div>
</footer>

    </div>
    <script type="text/javascript">
    $(window).on("load", function(){
      var cx = '009733439235723428699:lh9ltjgvdz8';
      var gcse = document.createElement('script');
      gcse.type = 'text/javascript';
      gcse.async = true;
      gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx;
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(gcse, s);
    });
    </script>

  </body>
</html>